package com.huluobo.koltinim2003a.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import com.huluobo.koltinim2003a.R
import org.jetbrains.anko.sp

/**
 * Created by lc on 2022/9/26.
 */
class SlideBar(context: Context, attributeSet: AttributeSet) : View(context, attributeSet) {
    companion object {
        private val SECTIONS = arrayOf(
            "A",
            "B",
            "C",
            "D",
            "E",
            "F",
            "G",
            "H",
            "I",
            "J",
            "K",
            "L",
            "M",
            "N",
            "O",
            "P",
            "Q",
            "R",
            "S",
            "T",
            "U",
            "V",
            "W",
            "X",
            "Y",
            "Z"
        )
    }

    var sectionHeight = 0f//给第一个item(SECTION)一个初始高度
    private var textBaseline = 0f//定义基准线

    private val paint = Paint()

    init {
        paint.apply {
            color = resources.getColor(R.color.qq_gray)
            textSize = sp(12).toFloat()

            //设置画笔居中对齐
            textAlign = Paint.Align.CENTER
        }
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        //计算每一个字符的高度(sectionHeight)
        //参数h 代表当前view的高度,字母条的高度
        sectionHeight = h * 1.0f / SECTIONS.size

        //获取绘制文字的尺寸
        val fontMetrics = paint.fontMetrics

        //计算绘制文本的高度
        val textHeight = fontMetrics.descent - fontMetrics.ascent

        //计算基准线 (Descent+Ascent)/2-Descent
//        textBaseline = (fontMetrics.descent + fontMetrics.ascent) / 2 - fontMetrics.descent
        textBaseline = sectionHeight / 2 + (textHeight / 2 - fontMetrics.descent)
    }

    override fun onDraw(canvas: Canvas?) {
        //绘制所有的字母
        val x = width * 1.0f / 2
//        var y = sectionHeight
        var baseline = textBaseline

        SECTIONS.forEach {
            canvas?.drawText(it, x, baseline, paint)
            baseline += sectionHeight
        }
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        when (event?.action) {
            MotionEvent.ACTION_DOWN -> setBackgroundColor(R.drawable.bg_slide_bar)
            MotionEvent.ACTION_UP -> setBackgroundColor(Color.TRANSPARENT)
        }
        return true //消费掉事件
    }

}